<template>
  <div class="container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="button-group">
        <el-button type="primary" plain :icon="Plus" @click="toCreateArticle">新增</el-button>
        <el-button type="success" plain :icon="Edit" :disabled="single" @click="handleUpdate1">修改</el-button>
        <el-button type="danger" plain :icon="Delete" :disabled="multiple" @click="handleDelete(-1)">删除</el-button>
      </div>

      <el-pagination
          v-model:current-page="page.currentPage"
          v-model:page-size="page.pageSize"
          :page-sizes="[5, 10, 15]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="articlesList"
        @selection-change="handleSelectionChange"
        @row-click="toArticle"
        class="article-table"
    >
      <!-- 表格列定义 -->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标题" prop="title" align="center" />
      <el-table-column label="点赞量" prop="like" align="center" />
      <el-table-column label="收藏" prop="subscribe" align="center" />

      <el-table-column label="封面" align="center" width="200">
        <template #default="{ row }">
          <el-image :src="row.pic" :preview-src-list="[row.pic]" class="cover-image">
            <template #error>
              <div class="image-error">加载失败</div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="类型" align="center">
        <template #default="{ row }">
          {{ showDictUtil(row.articleType, articleTypeDict) }}
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === '1' ? 'success' : 'danger'">
            {{ showDictUtil(row.status, articleStatusDict) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="创建人" prop="createBy" align="center" />

      <el-table-column label="创建日期" align="center" width="180">
        <template #default="{ row }">
          {{ parseTime(row.createTime, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>

      <el-table-column label="修改日期" align="center" width="180">
        <template #default="{ row }">
          {{ parseTime(row.updateTime, '{y}-{m}-{d}') }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="120">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle @click.stop="handleUpdate2(row)" />
          <el-button type="danger" :icon="Delete" circle @click.stop="handleDelete(row)" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { parseTime } from '@/tool/utils'
import { getArticleList, deleteArticle } from '@/api/articleApi'
import { getDict } from '@/api/common'
import { showDictUtil } from '@/tool/commonFun'

const router = useRouter()

// 响应式状态
const loading = ref(true)
const single = ref(true)
const multiple = ref(true)
const ids = ref([])
const articlesList = ref([])
const articleTypeDict = ref([])
const articleStatusDict = ref([])

const page = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
})

// 生命周期钩子
onMounted(async () => {
  await Promise.all([fetchArticles(), fetchDicts()])
})

// 数据获取
const fetchArticles = async () => {
  try {
    const res = await getArticleList(page)
    articlesList.value = res.data.articles
    page.total = res.data.total
  } finally {
    loading.value = false
  }
}

const fetchDicts = async () => {
  const [typeRes, statusRes] = await Promise.all([
    getDict({ value: 'wz_lx' }),
    getDict({ value: 'wz_zt' })
  ])
  articleTypeDict.value = typeRes.data[0].child
  articleStatusDict.value = statusRes.data[0].child
}

// 事件处理
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const deleteIds = row !== -1 ? [row.id] : ids.value
    await deleteArticle(deleteIds)

    ElMessage.success('删除成功')
    await fetchArticles()
  } catch (error) {
    // 取消删除不处理
  }
}

// 分页处理
const handleSizeChange = (size) => {
  page.pageSize = size
  fetchArticles()
}

const handleCurrentChange = (current) => {
  page.currentPage = current
  fetchArticles()
}

// 路由跳转
const toCreateArticle = () => router.push({ name: 'AddArticle' })
const handleUpdate1 = () => router.push({ name: 'AddArticle', query: { id: ids.value[0] } })
const handleUpdate2 = (row) => router.push({ name: 'AddArticle', query: { id: row.id } })
const toArticle = (row) => router.push(`/health/article/${row.id}`)
</script>

<style scoped>
.container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.article-table {
  margin-top: 20px;
}

.cover-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
}

.image-error {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  background: #f5f7fa;
}
</style>